﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Shell;
using ImageTools;
using ImageTools.IO;
using ImageTools.IO.Png;
using System.IO.IsolatedStorage;

namespace PressureDiary
{
    public partial class TileControl : UserControl
    {
        public TileControl()
        {
            InitializeComponent();
        }

        public StandardTileData ToTile()
        {
            // Need to call these, otherwise the contents aren't rendered correctly.
            this.Measure(new Size(173, 173));
            this.Arrange(new Rect(0, 0, 173, 173));

            // The png encoder is the work of the ImageTools API. http://imagetools.codeplex.com/
            ExtendedImage tileImaged = this.ToImage();

            Encoders.AddEncoder<PngEncoder>();

            var p = new PngEncoder();

            const string tempFileName = "/Shared/ShellContent/tileImage.png";

            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (myIsolatedStorage.FileExists(tempFileName))
                {
                    myIsolatedStorage.DeleteFile(tempFileName);
                }

                IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempFileName);
                p.Encode(tileImaged, fileStream);
                fileStream.Close();
            }

            var newTile = new StandardTileData
            {
                Title = App.ApplicationName,
                BackgroundImage =
                    new Uri("isostore:" + tempFileName, UriKind.RelativeOrAbsolute)
            };

            return newTile;
        }
    }
}
